package com.jeehentor.system.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeehentor.common.exception.HentorException;
import com.jeehentor.entity.SysDict;
import com.jeehentor.entity.SysDictItem;
import com.jeehentor.system.mapper.SysDictMapper;
import com.jeehentor.system.service.ISysDictItemService;
import com.jeehentor.system.service.ISysDictService;
import com.jeehentor.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.jeehentor.common.constant.CacheConstants.DICT_DETAILS;

/**
 * <p>
 * 字典表 服务实现类
 * </p>
 *
 * @author wzd
 * @since 2024-04-29
 */
@Service
@RequiredArgsConstructor
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements ISysDictService {
    private final ISysDictItemService dictItemService;
    private final RedisUtils redisUtils;

    @Override
    public void saveDict(SysDict sysDict) {
        LambdaQueryWrapper<SysDict> dictLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dictLambdaQueryWrapper.eq(SysDict::getDictCode,sysDict.getDictCode());
        SysDict one = this.getOne(dictLambdaQueryWrapper);
        if(one != null){
            throw new HentorException("字典编码已存在");
        }
        this.save(sysDict);
    }

    @Override
    public void updateDict(SysDict sysDict) {
        LambdaQueryWrapper<SysDict> dictLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dictLambdaQueryWrapper.eq(SysDict::getDictCode,sysDict.getDictCode());
        dictLambdaQueryWrapper.ne(SysDict::getId,sysDict.getId());
        SysDict one = this.getOne(dictLambdaQueryWrapper);
        if(one != null){
            throw new HentorException("字典编码已存在");
        }
        this.updateById(sysDict);
        cacheDictItem(sysDict.getDictCode());
    }

    @Override
    public void delDict(SysDict sysDict) {
        this.removeById(sysDict);
        delCacheDictItem(sysDict.getId());
        dictItemService.remove(new QueryWrapper<SysDictItem>().eq("dict_id", sysDict.getId()));
    }

    @Override
    public List<SysDictItem> getDictItemByCode(String dictCode) {
        Object o = redisUtils.getValueOperations().get(DICT_DETAILS + dictCode);
        if(o != null){
            return JSON.parseArray(JSON.toJSONString(o), SysDictItem.class);
        }else {
            LambdaQueryWrapper<SysDictItem> dictItemLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dictItemLambdaQueryWrapper.eq(SysDictItem::getDictCode, dictCode);
            List<SysDictItem> list = dictItemService.list(dictItemLambdaQueryWrapper);
            redisUtils.getValueOperations().set(DICT_DETAILS + dictCode, list);
            return list;
        }
    }

    @Override
    public void batchDelDict(List<String> ids) {
        if(CollectionUtil.isNotEmpty(ids)){
            ids.forEach(x->{
                this.removeById(x);
                QueryWrapper<SysDictItem> queryWrapper = new QueryWrapper<SysDictItem>().eq("dict_id", x);
                delCacheDictItem(x);
                dictItemService.remove(queryWrapper);
            });
        }
    }

    @Override
    public void saveDictItem(SysDictItem sysDictItem) {
        LambdaQueryWrapper<SysDictItem> dictItemLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dictItemLambdaQueryWrapper.eq(SysDictItem::getDictId, sysDictItem.getDictId());
        dictItemLambdaQueryWrapper.eq(SysDictItem::getItemText, sysDictItem.getItemText());
        SysDictItem one = dictItemService.getOne(dictItemLambdaQueryWrapper);
        if(ObjectUtil.isNotNull(one)){
            throw new HentorException("字典项已存在");
        }
        dictItemService.save(sysDictItem);
        cacheDictItem(sysDictItem.getDictCode());
    }

    @Override
    public void delDictItem(SysDictItem sysDictItem) {
        SysDictItem byId = dictItemService.getById(sysDictItem.getId());
        delCacheDictItem(byId.getDictId());
        dictItemService.removeById(sysDictItem);
    }

    @Override
    public void updateDictItem(SysDictItem sysDictItem) {
        LambdaQueryWrapper<SysDictItem> dictItemLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dictItemLambdaQueryWrapper.eq(SysDictItem::getDictId, sysDictItem.getDictId());
        dictItemLambdaQueryWrapper.eq(SysDictItem::getItemText, sysDictItem.getItemText());
        dictItemLambdaQueryWrapper.ne(SysDictItem::getId, sysDictItem.getId());
        SysDictItem one = dictItemService.getOne(dictItemLambdaQueryWrapper);
        if(ObjectUtil.isNotNull(one)){
            throw new HentorException("字典项已存在");
        }
        dictItemService.updateById(sysDictItem);
        cacheDictItem(sysDictItem.getDictCode());
    }

    private void delCacheDictItem(String dictId){
        QueryWrapper<SysDictItem> queryWrapper = new QueryWrapper<SysDictItem>().eq("dict_id", dictId);
        List<SysDictItem> list = dictItemService.list(queryWrapper);
        //删除缓存
        List<String> dictKeys = list.stream().map(f -> DICT_DETAILS + f.getDictCode()).collect(Collectors.toList());
        redisUtils.common.delete(dictKeys);
    }

    private void cacheDictItem(String dictCode){
        LambdaQueryWrapper<SysDictItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictItem::getDictCode, dictCode);
        List<SysDictItem> list = dictItemService.list(queryWrapper);
        List<SysDictItem> dictItems = list.stream().filter(sysDictItem -> "1".equals(sysDictItem.getStatus())).collect(Collectors.toList());
        redisUtils.getValueOperations().set(DICT_DETAILS+dictCode, dictItems, 12, TimeUnit.HOURS);
    }
}
